package madixin.t107;

import javafx.util.Pair;

import java.util.*;

class Solution {
    public List<List<Integer>> levelOrderBottom(TreeNode root) {
        List<List<Integer>> res = new ArrayList<>();
        if (root == null) {
            return res;
        }
        Queue<TreeNode> queue = new LinkedList<>();
        Stack<List<Integer>> stackRes = new Stack<>();
        queue.add(root);
        while (!queue.isEmpty()) {
            int size = queue.size();
            List<Integer> list = new LinkedList<>();
            for (int i = 0; i < size; i++) {
                TreeNode curNode = queue.remove();
                list.add(curNode.val);
                if (curNode.left != null) {
                    queue.add(curNode.left);
                }
                if (curNode.right != null) {
                    queue.add(curNode.right);
                }
            }
            stackRes.push(list);
        }
        while (!stackRes.isEmpty()) {
            res.add(stackRes.pop());
        }
        return res;
    }

    public List<List<Integer>> levelOrderBottom1(TreeNode root) {
        List<List<Integer>> res = new ArrayList<>();
        if (root == null) {
            return res;
        }
        Stack<Pair<TreeNode, Integer>> stack = new Stack<>();
        Integer level = 0;
        stack.push(new Pair<TreeNode, Integer>(root, level));
        while (!stack.isEmpty()) {
            Pair<TreeNode, Integer> cur = stack.pop();
            TreeNode curNode = cur.getKey();
            Integer curLevel = cur.getValue();
            if (res.size() <= curLevel) {
                List<Integer> list = new LinkedList<>();
                res.add(list);
            }
            res.get(curLevel).add(curNode.val);

            if (curNode.left != null) {
                stack.push(new Pair<TreeNode, Integer>(curNode.left, curLevel + 1));
            }
            if (curNode.right != null) {
                stack.push(new Pair<TreeNode, Integer>(curNode.right, curLevel + 1));
            }
        }
        Collections.reverse(res);
        return res;
    }
}